import { delay } from 'redux-saga'

export default {
    namespace: 'todos',
    state: [],
    effects: {
        *deleteAfter1Second(action, { put, call, take, all, race }) {
            console.log('deleteAfter1Second', { action, delay, take, all, race })
            // 延时1秒
            yield call(delay, 1000)
            // 调用reducers中的delete
            yield put({ type: 'delete', payload: action.payload })
            // 调用*logAfter1Second
            yield put({ type: 'logAfter1Second', payload: action.payload })
            // 调用另一个model中的effect
            yield put({ type: 'products/logAfter1Second', payload: '啊哈哈哈' })

            // 调用另一个model中的reducer并等待回调
            const productsLog = yield take('products/log')

            // 拿到回调后再次调用另一个model中的effect
            console.log({ productsLog })
            yield put({ type: 'products/logAfter1Second', payload: productsLog.payload + ',鸡汤来咯!' })

            // 并行,同时调用俩函数并等待他俩执行完成拿到回调
            const [result1, result2] = yield all([
                call(console.log, { param: '喝啊' }),
                call(console.log, { param: '快喝啊' }),
            ])

            // 竞争，谁先执行完就结束，拿到执行完的那个回调
            const { posts, timeout } = yield race({
                posts: call(word => {
                    console.log(word)
                    return true
                }, '天皇陛下'),
                timeout: call(delay, 1000)
            })
            console.log({ posts, timeout })
            if (posts) {
                console.log('我滴任务完成啦')
            } else {
                console.log('穿山甲被炸死了')
            }



            console.log({ result1, result2 })



            return 'tnnd'
        },
        *logAfter1Second(action, { put, call }) {
            console.log('logAfter1Second', { action })
            yield call(delay, 1000)
            yield put({ type: 'log', payload: action.payload })
        }
    },
    reducers: {
        'delete'(state, { payload: id }) {
            console.log('delete', { id })
            return state.filter(item => item.id !== id);
        },
        log(state, { payload }) {
            console.log('todos/log', { state, payload })
            return state
        }
    },
}